extends Node2D

@onready var tile_map_layer = %TileMapLayer
@onready var player = %player

var path: Array[Vector2i]  # 存储A*算法返回的路径
var speed: float = 100.0  # 移动速度

var 地图范围:Array[Vector2i]=[]
var 障碍区:Array[Vector2i]=[]
var astar=MyAstar.new()

func _ready():
	地图范围=tile_map_layer.get_used_cells()
	障碍区=tile_map_layer.get_used_cells_by_id(0,Vector2i(5,1))

func _process(delta: float) -> void:
	if path.is_empty():
		return  # 没有路径时不移动
		
	# 计算目标位置
	var target_position = tile_map_layer.map_to_local(path.front())-player.size/2

	# 计算当前节点到目标节点的方向
	var direction = (target_position - player.position).normalized()
	
	# 移动
	player.position += direction * speed * delta

	# 检查是否到达目标
	if player.position.distance_to(target_position) < 0.5:  # 0.5是到达目标的容差
		path.pop_front()

# 处理鼠标左键点击事件
func _input(event: InputEvent) -> void:
	if event is InputEventMouseButton and event.button_index == MOUSE_BUTTON_LEFT and event.pressed:
		var target_pos = tile_map_layer.local_to_map(event.position)
		calculate_path_to(target_pos)

# 使用 A* 算法计算路径
func calculate_path_to(target_pos: Vector2i) -> void:
	path = []  # 清空之前的路径
	
	var start_pos=tile_map_layer.local_to_map(player.position)
	path = astar.AStarSearch(地图范围,障碍区,start_pos,target_pos)
	# 确保路径不为空
	if path.size() > 0:
		path.pop_front()  # 如果路径包含起始点，移除它
